#!/bin/bash
attempt=0
while true; do
  /opt/kubernetes/bin/etcdctl --ca-file /opt/kubernetes/ssl/ca.pem --cert-file /opt/kubernetes/ssl/flanneld.pem --key-file /opt/kubernetes/ssl/flanneld-key.pem \
    --no-sync -C {{ ETCD_ENDPOINTS }} \
    get {{ FLANNEL_ETCD_PREFIX }}/config >/dev/null 2>&1
  if [[ "$?" == 0 ]]; then
    break
  else
    if (( attempt > 20 )); then
      echo "timeout for waiting network config" > /opt/kubernetes/log/flannel-error.log
      exit 2
    fi

    /opt/kubernetes/bin/etcdctl --ca-file /opt/kubernetes/ssl/ca.pem --cert-file /opt/kubernetes/ssl/flanneld.pem --key-file /opt/kubernetes/ssl/flanneld-key.pem \
      --no-sync -C {{ ETCD_ENDPOINTS }} \
      mk {{ FLANNEL_ETCD_PREFIX }}/config "{\"Network\":\"{{ POD_CIDR }}\", \"Backend\": { \"Type\": \"vxlan\"}}" >/dev/null 2>&1
    attempt=$((attempt+1))
    sleep 3
  fi
done
wait
